# -*- coding: utf-8 -*-
import logging
import cgi, os, sys
import plistlib
from google.appengine.ext.webapp import template, \
        WSGIApplication
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from iphone.model import *

class StaticPages(webapp.RequestHandler):
    def get(self):
        #path = os.path.join(os.path.dirname(__file__), 'views/phone/')
        #self.response.out.write(template.render(path, None))
        cats = Category.allTops()
        presses = Press.all()
        vals = {
            'cats': cats,
            'presses': presses
        }
        path = os.path.join(os.path.dirname(__file__), 'views/admin/bookadd.html')
        #print path
        self.response.out.write(template.render(path, vals))


class BookAdd(webapp.RequestHandler):
    def post(self):
        book = Book()
        
        book.name = self.request.get('name')
        book.author = self.request.get('author')
        pid = self.request.get('cid')
        pressId = self.request.get('pressId')
        cover = self.request.get('cover')
        filename = self.request.get('filename')
        mtype = self.request.get('fileext')
        coverStory = self.request.get('coverStory')
        price = self.request.get('price')
        
        try:
            pid = long(pid)
            pressId = long(pressId)
            price = float(price)
        except:
            price = 0.0
            logging.info('add book error!!')
        if cover:
            media = Media(name = filename, mtype = mtype, bits = cover).put()
            book.cover = media
        if pid and pid != 0:
            book.category = Category.get_by_id(pid)
        if pressId and pressId != 0:
            book.press = Press.get_by_id(pressId)
        book.coverStory = coverStory
        book.price = price
        book.save()
        update = UpdateInfo.all()[0]
        logging.info('update is none?')
        if update:
            logging.info('update is not none.')
            update.save()
        else:
            UpdateInfo(version=0.9).save()
        #logging.info('book name is ' + book.name)
        self.redirect('/phone/list')

class BookList(webapp.RequestHandler):
    def get(self):
        books = Book.all()
        #for book in books:
        #    logging.info('book id is ' + str(book.key().id()))
        path = os.path.join(os.path.dirname(__file__), 'views/admin/booklist.html')
        template_values = {
            'books': books,
        }
        self.response.out.write(template.render(path, template_values))

class BookDelete(webapp.RequestHandler):
    def get(self):
        id = long(self.request.get('id'))
        #logging.info(id)

        book = Book.get_by_id(id)
        book.delete()
        self.redirect('/phone/list')

class CategoryManager(webapp.RequestHandler):
    def get(self):
        action = self.request.get('action')
        #action = self.param('action')
        pid = self.request.get('pid')
        
        if action == 'edit':
            pass
        elif action == 'delete':
            id = long(self.request.get('id'))
            Category.get_by_id(id).delete()
            self.redirect('/phone/categories')
        else:
            action = 'add'
        path = os.path.join(os.path.dirname(__file__), 'views/admin/category.html')
        categories = Category.allTops()
        vals = {'action': action, 'cats': categories}
        self.response.out.write(template.render(path, vals))

    def post(self):
        action = self.request.get('action')
        name = self.request.get('name')
        pid = self.request.get('pid')
        desc = self.request.get('desc')
        
        try:
            pid = int(pid)
        except:
            pid = 0
        if pid == 0:
            pid = None
        else:
            pid = Category.get_by_id(pid)
        if action == 'add':
            cat = Category(name = name, parentCategory = pid, desc = desc)
            cat.save()
            self.redirect('/phone/categories')

class Categories(webapp.RequestHandler):
    def get(self):
        #categories = Category.all()
        cats=Category.allTops()
        path = os.path.join(os.path.dirname(__file__), 'views/admin/categories.html')
        vals = {
            #'categories': categories,
            'cats':cats,
        }
        self.response.out.write(template.render(path, vals))

class PressManager(webapp.RequestHandler):
    def get(self):
        action = self.request.get('action')
        key = self.request.get('key')
        press = None
        
        if action == 'edit':
            try:
                press = Press.get(key)
                logging.info('got it!')
            except Exception:
                logging.info(Exception)
        elif action == 'delete':
            id = long(self.request.get('id'))
            Press.get_by_id(id).delete()
            self.redirect('/phone/presses')
        else:
            action = 'add'
       
        vals = {'press': press, 'action': action}
        path = os.path.join(os.path.dirname(__file__), 'views/admin/press.html')
        self.response.out.write(template.render(path, vals))
    
    def post(self):
        action = self.request.get('action')
        name = self.request.get('name')
        desc = self.request.get('desc')

        if action == 'add':
            press = Press(name = name, desc = desc)
            press.save()
            self.redirect('/phone/presses')

class Presses(webapp.RequestHandler):
    def get(self):
        presses = Press.all()
        path = os.path.join(os.path.dirname(__file__), 'views/admin/presses.html')
        vals = {
            #'categories': categories,
            'presses':presses,
        }
        self.response.out.write(template.render(path, vals))

class FileManager(webapp.RequestHandler):
    def get(self):
        files = Media.all().order('-date')
        vals = {'files': files}
        path = os.path.join(os.path.dirname(__file__), 'views/admin/filemanager.html')
        self.response.out.write(template.render(path, vals))

class GetMedia(webapp.RequestHandler):
    def get(self, slug):
        media = Media.get(slug)
        
        if media:
            self.response.headers['Expires'] = 'Thu, 17 Apr 3010 00:00:00 GMT'
            self.response.headers['Cache-Control'] = 'max-age=3600,public'
            self.response.headers['Content-Type'] = str(media.mtype)
            self.response.out.write(media.bits)
            a = self.request.get('a')
            if a and a.lower() == 'download':
                media.download += 1
                media.put()

class MediaManager(webapp.RequestHandler):
    #@requires_admin
    def get(self):
        action = self.request.get('action')
        key = self.request.get('id')
        
        if action and action == 'delete':
            Media.get(key).delete()
        self.redirect('/phone/filemanager')

class CheckUpdate(webapp.RequestHandler):
    def get(self):
        updateInfo = UpdateInfo.all()[0]
        if updateInfo:
            plist = {'mc_last_update': updateInfo.lastUpdated, 'mc_version': round(updateInfo.version, 1)}
        else:
            import time
            plist = {'mc_last_update': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), 'mc_version': 0.0}

        self.response.headers['Content-Type'] = 'text/xml'
        self.response.out.write(plistlib.writePlistToString(plist))

def main():
    #webapp.template.register_template_library('filter')
    webapp.template.register_template_library('app.recurse')
    application = webapp.WSGIApplication([('/phone/add', BookAdd),
                                          ('/phone/list', BookList),
                                          ('/phone/delete', BookDelete),
                                          ('/phone/category', CategoryManager),
                                          ('/phone/categories', Categories),
                                          ('/phone/press', PressManager),
                                          ('/phone/presses', Presses),
                                          ('/phone/filemanager', FileManager),
                                          ('/phone/media', MediaManager),
                                          ('/phone/media/([^/]*)/{0,1}.*',GetMedia),
                                          ('/phone/check', CheckUpdate),
                                          ('/phone/.*', StaticPages),
                                     ], debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
